/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Facades;


import com.dpy.appmvdpy.Models.*;
import java.util.List;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Lilli
 */
@Component
@Scope(value="request")
public class PedidosFacade extends DefaultFacade<Pedidos> {
   
    @Autowired
    public ProdutosPedidosFacade facade;
    
    public PedidosFacade()
    {
       super(Pedidos.class);
    }
     
    @Override
    public void setId(Pedidos entity) {
  //      entity.setId(this.getMaxId() + 1);
    }  
    
    @Transactional(readOnly=true)
    public List<Pedidos> listAll()
    {
       Query q = em.createQuery("SELECT c from Pedidos as c ORDER BY c.integrado ASC, p.data DESC");
       return q.getResultList();
    }
      
    @Transactional(readOnly=true)
    public List<Pedidos> listAll(int pag)
    {
       Query q = em.createQuery("SELECT c from Pedidos as c ORDER BY c.integrado ASC, c.data DESC");
       q.setFirstResult(pag * 100);
       q.setMaxResults(100);
       return q.getResultList();
    }
    
      @Transactional(readOnly=true)
    public List<Pedidos> listAll(Vendedor v)
    {
       Query q = em.createQuery("SELECT c from Pedidos as c WHERE c.vendedor.id = :vid ORDER BY c.integrado ASC, p.data DESC");
       q.setParameter("vid", v.getId());
       return q.getResultList();
    }
      
    @Transactional(readOnly=true)
    public List<Pedidos> listAll(int pag, Vendedor v)
    {
       Query q = em.createQuery("SELECT c from Pedidos as c WHERE c.vendedor.id = :vid ORDER BY c.integrado ASC, c.data DESC");
       q.setParameter("vid", v.getId());
       q.setFirstResult(pag * 100);
       q.setMaxResults(100);
       return q.getResultList();
    }
    
    @Transactional(readOnly=true)
    public Integer getLastCodigoDpy(Vendedor vendedor)
    {
       Query q = em.createQuery("SELECT coalesce(max(c.codigoDPY),0) from Pedidos as c WHERE c.vendedor.id = :id");
       q.setParameter("id", vendedor.getId());
       return (Integer)q.getSingleResult();
    }
        
    @Transactional
    @Override
    public void delete(int id) {
        Pedidos p = this.getById(id);
    
       
        for(ProdutosPedidos pp: p.getProdutosPedidosCollection())
                   pp.getIdPRODUTOS().getProdutosPedidosCollection().clear();
        p.getProdutosPedidosCollection().clear();
        super.delete(id);
    }
   
    
    }
